/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.opgea.token.listeners;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.opgea.token.domain.constants.ApplicationConstants;
import com.opgea.token.domain.entities.Company;
import com.opgea.token.domain.model.CurrentTokenModel;
import com.opgea.token.util.HibernateUtil;

/**
 * 
 * @author Ramesh
 */
@Service
public class TokenContextLoaderListener implements ServletContextListener {

    public static Map<Long, CurrentTokenModel> currentTokenMap = new HashMap<Long, CurrentTokenModel>();

    private Session session = HibernateUtil.getSessionFactory().openSession();

    @SuppressWarnings("unchecked")
    public List<Company> findAllCompanies() {
	List<Company> companies = session.createQuery("from Company").list();
	return companies;
    }

    public Integer getMaxTokenNumber(Long companyId, String dateString) {
	/*
	 * Date today = Calendar.getInstance(Locale.US).getTime();
	 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String
	 * dateString = sdf.format(today);
	 */
	Query query = session.createQuery("SELECT max(t.tokenNo) FROM Token t "
		+ " WHERE t.company.id = " + companyId + " AND "
		+ " t.tokenDate = '" + dateString + "' ");
	System.out.println("TokenContextLoaderListener: "
		+ query.getQueryString());
	return (Integer) query.uniqueResult();
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
	Date today = Calendar.getInstance(Locale.US).getTime();
	SimpleDateFormat sdf = new SimpleDateFormat(ApplicationConstants.YYYY_MM_DD);
	String dateString = sdf.format(today);

	ServletContext servletContext = sce.getServletContext();

	servletContext.setAttribute(
		ApplicationConstants.CURRENT_TOKEN_MAP,
		currentTokenMap);
	System.out.println("Token Context Loader Initialized...");

	List<Company> companies = this.findAllCompanies();
	if (companies != null) {
	    for (Company company : companies) {
		CurrentTokenModel model = new CurrentTokenModel();
		model.setCompanyId(company.getId());
		model.setCurrentTokenNumber(this.getMaxTokenNumber(
			company.getId(), dateString));
		model.setToday(Calendar.getInstance().getTime());
		currentTokenMap.put(company.getId(), model);
	    }
	}

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
	ServletContext servletContext = sce.getServletContext();
	servletContext.removeAttribute(ApplicationConstants.CURRENT_TOKEN_MAP);
	System.out.println("Token Context Loader Destroyed...");
    }

}
